/**
* @Title: monitorMap_ctrl.js
* @Description: TODO
* Copyright: Copyright (c) 2014 
 * Company:中国平安
*
* @Project HIMS-FWA
* @author WANGSHUYAN202
* @date 2014年9月5日 下午3:01:45
* @version V1.0
*/
;
(function(){
	'use strict';
	var app = angular.module('fwa.mainApp');
	app.controller('monitorIntegrityMapCtrl',
			['$scope','$state','Modal','MonitorIntegrityService','MonitorIntegrity',
	          function($scope,$state, Modal,MonitorIntegrityService,MonitorIntegrity){
				$scope.monitorIntegrity = MonitorIntegrity;
				//首次判断百度地图是否已经加载完毕
				var map = null;
				function initBaiduMap(){
					if(map != null){
						return map;
					}
					try{
					    map = new BMap.Map("monitorIntegrityMap",{minZoom:10,maxZoom:11});   // 创建Map实例,设置地图允许的最小/大级别
					}
					catch(e){
						if(confirm("加载百度地图API失败,是否重新加载？")){
							initBaiduMap();
						}
					}
					return map;
				}
				initBaiduMap();
				//初始化百度地图				
				map.centerAndZoom("厦门",10);                                // 初始化地图,设置中心点坐标和地图级别	
				var styleJson = [
	           					 {
	  					                    "featureType": "land",
	  					                    "elementType": "all",
	  					                    "stylers": {
	  					                              "color": "#004682",
	  					                              "hue": "#004682"
	  					                    }
	  					          },  
	  						      {
	  					                    "featureType": "green",
	  					                    "elementType": "all",
	  					                    "stylers": {
	  					                              "color": "#004682",
	  					                              "hue": "#004682",
	  					                              "visibility": "on"
	  					                    }
	  					          },
	  						      {
	  					                    "featureType": "highway",
	  					                    "elementType": "geometry",
	  					                    "stylers": {
	  					                              "color": "#005695",
	  					                              "hue": "#005695",
	  					                              "weight": "0.3",
	  					                              "lightness": -2,
	  					                              "visibility": "off"
	  					                              
	  					                    }
	  					          },
	  					          {
	  					                    "featureType": "water",
	  					                    "elementType": "all",
	  					                    "stylers": {
	  					                              "color": "#003f63",
	  					                              "hue": "#003f63"
	  					                    }
	  					          },
	  					          {
	  					                    "featureType": "boundary",
	  					                    "elementType": "geometry",
	  					                    "stylers": {
	  					                              "color": "#00ccff",
	  					                              "hue": "#00ccff"
	  					                    }
	  					          },
	  					          {
	  					                    "featureType": "road",
	  					                    "elementType": "all",
	  					                    "stylers": {
	  					                              "color": "#004682"
	  					                    }
	  					          },
	  						      {
	  					                    "featureType": "road",
	  					                    "elementType": "labels.icon",
	  					                    "stylers": {
	  					                              "visibility": "off"
	  					                    }
	  					          },
	  						      {
	  					                    "featureType": "label",
	  					                    "elementType": "all",
	  					                    "stylers": {
	  					                              "visibility": "off"
	  					                    }
	  					          },
	  						      {
	  					                    "featureType": "poi",
	  					                    "elementType": "all",
	  					                    "stylers": {
	  					                              "visibility": "off"
	  					                    }
	  					          }
				  						  
				  		]
			//异步加載,需将操作地图代码放在load方法里面	
			map.addEventListener("load", function(){ 
				map.addControl(new BMap.OverviewMapControl());              // 添加缩略地图控件
				map.enableScrollWheelZoom();                                // 启用滚轮放大缩小
				map.setMapStyle({
					  features: ["road", "building","water","land"],             // 隐藏地图上的poi
					  styleJson: styleJson			  
					});
			   
			});
			
			//监控查询条件修改
			$scope.$watch('monitorIntegrity.params',function(v){
				if (v) {
					queryMonitorIntegrityMap(v);
				}
			});
			//不同地区不同机构类型的值
			var  mapDtos = [] ;
			
			//存储两个违反最多的两个地区集合
			var oneDatas = [],twoDatas = [];
			
			var areaDatas = [
			                 {areaDesc:"厦门",areaCode:"",num:"0"},
			                 {areaDesc:"湖里区",areaCode:"A0101",num:"0"},
			                 {areaDesc:"思明区",areaCode:"A0102",num:"0"},
			                 {areaDesc:"集美区",areaCode:"A0103",num:"0"},
			                 {areaDesc:"同安区",areaCode:"A0104",num:"0"},
			                 {areaDesc:"翔安区",areaCode:"A0105",num:"0"},
			                 {areaDesc:"海沧区",areaCode:"A0106",num:"0"}
			                 ];
			//查询
			function queryMonitorIntegrityMap(params) {
				MonitorIntegrityService.queryMonitorIntegrityMap(params)
				.success(function(res){
					if (res.state == '1') {
						Modal.alert(res.msg);
					} 
					else {
						mapDtos = res.mapDtos;
						if (res.areaDatas) {
							getBoundary("厦门",'');
							getFillColorData(res.areaDatas);
							angular.forEach(res.areaDatas,function(data,index){
								getBoundary(data.areaDesc,data.areaCode);
							});
						}
						else {
							angular.forEach(areaDatas,function(data,index){
								getBoundary(data.areaDesc,data.areaCode);
							});
						}
					}
				});
			}
			
			function getFillColorData(areaDatas) {
				var datas = [];
				angular.forEach(areaDatas,function(areaData,index){
					var num = 0;
					angular.forEach(mapDtos,function(data,index){
						if (areaData.areaCode == data.areaCode) {
							num = num + parseInt(data.num);
						} 
					});
					datas.push({"areaCode":areaData.areaCode,"num":num});
				});
				//排序 最大值在上面
				datas.sort(function(a,b){
					var num1 = a.num;
					var num2 = b.num;
			        if (num2 > num1) {   
			        	return 1; 
		        	}
			        else if (num2 == num1) { 
		        		return 0;     
	        		}
			        else {    
	        			return -1;   
	    			}
				});
				//获取扣分第一的地区 以及第二的地区
				var towIndex = 0;
				angular.forEach(datas,function(data,index){
					if (datas[0].num == datas[index].num) {
						if (datas[towIndex].num > 0) {
							oneDatas.push(datas[index]);
						}
					}
					else {
						if (towIndex == 0) {
							towIndex = index;
						}
						if (datas[towIndex].num == datas[index].num) {
							twoDatas.push(datas[index]);
						}
					}
				});
				
			}
			$scope.monitorMap = {};
			//数据组合
			function groupMonitorIntegrityMap(areaCode) {
				$scope.monitorMap = {};
				angular.forEach(mapDtos,function(data,index){
					//三级
					if (data.areaCode == areaCode 
						&& data.orgLevel == 4) {
						$scope.monitorMap.one = data.num;
					}
					//二级
					if (data.areaCode == areaCode
						&& data.orgLevel == 3) {
						$scope.monitorMap.two = data.num;
					}
					//一级
					if (data.areaCode == areaCode
						&& data.orgLevel == 2) {
						$scope.monitorMap.three = data.num;
					}
					//药店
					if (data.areaCode == areaCode
						&& data.orgLevel == 6) {
						$scope.monitorMap.drugstore = data.num;
					}
				});
			}
			
			var infoContainer = false;
			//弹出层隐藏
			$scope.popUpLayerHide = function(){
				$(".monitorIntegrity .integrityMap-info-container").hide();
			}
			//弹出层显示
			$scope.popUpLayerShow = function(){
				infoContainer = false;
				$(".monitorIntegrity .integrityMap-info-container").show();
			}
			
             //绘制边界折线
			function getBoundary(cityName,areaCode){
			    var bdary = new BMap.Boundary();
			    bdary.get(cityName, function(rs){       	   //获取行政区域
			    	var count = rs.boundaries.length; 	//行政区域的点有多少个
			        for(var i = 0; i < count; i++){
			        	var stroke = {strokeWeight: 1, strokeColor: "#00ccff",fillColor: ""};
			        	angular.forEach(oneDatas,function(data,index){
			        		if (data.areaCode == areaCode) {
			        			stroke.fillColor = "#a15861";
			        		}
			        	});
			        	angular.forEach(twoDatas,function(data,index){
			        		if (data.areaCode == areaCode) {
			        			stroke.fillColor = "#b29625";
			        		}
			        	});
			            var ply = new BMap.Polygon(rs.boundaries[i], stroke); //建立多边形覆盖物
			            map.addOverlay(ply);  				//添加覆盖物

			            if (cityName == '厦门') {
			            	map.setViewport(ply.getPath());    	//调整视野         
			            }
			            else {
			            	Markers(ply,areaCode,cityName);
			            }
			            
			        }                
			    });

			}
			$scope.areaCode = '';
            function Markers(ply,areaCode,areaName) {
	            ply.addEventListener("mousemove", function(e){
					var pointTest = new BMap.Point(e.point.lng,e.point.lat);
					var pixel = map.pointToPixel(pointTest);
					var left = pixel.x + 10;
					var top = pixel.y - 10 ;
					groupMonitorIntegrityMap(areaCode);
					$scope.areaName = areaName;
					$scope.popUpLayerShow();
					$scope.$apply();
					$(".monitorIntegrity .integrityMap-info-container").css("top",top + 'px');
					$(".monitorIntegrity .integrityMap-info-container").css("left",left +'px');
				});		
	            ply.addEventListener("mouseout", function(e){
	            	infoContainer = true;
					setTimeout(function(){
						if(infoContainer){
							$scope.popUpLayerHide();
						}
					},400);
				});
            }

			function checkhHtml5()   
	        {   
	            if (typeof(Worker) === "undefined")     
	            {   
	                if(navigator.userAgent.indexOf("MSIE 9.0")<=0)  
					   {  
					 	 alert("定制个性地图示例：IE9以下不兼容，推荐使用百度浏览器、chrome、firefox、safari、IE10");   
					   }  
	                
	            }  
	        }
	     	 checkhHtml5();  
 	}]);
})();